﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using eShop.DataAccess;
using eShop.Model;
using ECommerce.Library.DataStructure;
using AutoGear.BLL;
using System.IO;
using ECommerce.Library;
using log4net;
using System.Text;

namespace eShop.Business
{
    public class ManufacturerManager
    {
        
        public static ReadWriteCustomCollection<Manufacturer> FilterBrand(FilterType filterType)
        {
            ECommerce.DAL.CustomCollection<Manufacturer> brandData = null;

            if (filterType == FilterType.All)
                brandData = ManufacturerDAO.GetActiveProductBrands(1000);
            else
                brandData = ManufacturerDAO.GetProductBrandsByPrefix(filterType.ToString());

            ReadWriteCustomCollection<Manufacturer> brands = LoadFromCustomCollection(brandData);

            return brands;
        }

        
        public static ECommerce.DAL.CustomCollection<Manufacturer> Brands(bool includeDeleted)
        {
            if (includeDeleted)
                return ManufacturerDAO.GetAllTblProductBrand();
            else
                return ManufacturerDAO.GetNonDeletedBrands();
        }

        
        public static ReadWriteCustomCollection<Manufacturer> FeaturedBrands(int howMany)
        {
            ECommerce.DAL.CustomCollection<Manufacturer> brandData = ManufacturerDAO.GetFeaturedProductBrands(howMany);

            ReadWriteCustomCollection<Manufacturer> brands = LoadFromCustomCollection(brandData);

            return brands;
        }

        
        public static ReadWriteCustomCollection<Manufacturer> ActiveBrands(int howMany)
        {
            ECommerce.DAL.CustomCollection<Manufacturer> brandData = ManufacturerDAO.GetActiveProductBrands(howMany);

            ReadWriteCustomCollection<Manufacturer> brands = LoadFromCustomCollection(brandData);

            return brands;
        }

        
        public static ReadWriteCustomCollection<Product> GetActiveBrandProductsPaged(int productBrandId, string displayOrder, int currentPageIndex, int pageSize)
        {
            ReadWriteCustomCollection<Product> products = new ReadWriteCustomCollection<Product>();
            products = Product.ProductByManufacturer(productBrandId, currentPageIndex, pageSize, DataState.Active);
            return products;
        }

        
        public static int GetActiveBrandProductsCount(int productBrandId)
        {
            return Product.ProductCountByManufacturer(productBrandId, DataState.Active);
        }

        
        public static ReadWriteCustomCollection<Manufacturer> Brands(int howMany, bool chooseActive, bool chooseFeatured, bool chooseDeleted)
        {
            ECommerce.DAL.CustomCollection<Manufacturer> brandData = ManufacturerDAO.GetProductBrandsByCondition(howMany,
                chooseActive, chooseFeatured, chooseDeleted);

            ReadWriteCustomCollection<Manufacturer> brands = LoadFromCustomCollection(brandData);

            return brands;
        }

        
        public static Manufacturer Create(string brandName, string brandDescription, string logoTemporaryFilePath, bool isActive, bool isFeatured, string brandCode)
        {
            try
            {
                int newBrandId = 0;

                brandName = Security.BindStringInput(brandName, SecurityLevel.Zero);
                string brandUrl = SiteUtility.CleanBrandName(brandName);
                brandDescription = Security.BindStringInput(brandDescription, SecurityLevel.Zero);
                logoTemporaryFilePath = Security.BindStringInput(logoTemporaryFilePath, SecurityLevel.Zero);


                // counting how many brand has same name
                int count = ManufacturerDAO.GetProductBrandCountByName(brandName);
                string brandLogo = string.Empty;
                if (!String.IsNullOrEmpty(logoTemporaryFilePath))
                {
                    brandLogo = ProductFileAccessUtility.UploadImage(ProductFileAccessUtility._brandLogoPath, logoTemporaryFilePath);
                }


                // If no other brand has the same name, 
                // we create it.
                if (count <= 0)
                {
                    newBrandId = ManufacturerDAO.CreateNewTblProductBrand(brandName, brandDescription, string.Empty, brandUrl, isActive, string.Empty);

                    //TblProductBrand productBrandData = new TblProductBrand(newBrandId, brandName, brandDescription, string.Empty, brandUrl,
                    //    string.Empty, catalogFileFormat, catalogFileName, isActive, isFeatured, false, DateTime.Now, Convert.ToDecimal(productPricePercentage));

                    Manufacturer newBrand = new Manufacturer(newBrandId, brandName, brandDescription, string.Empty, brandUrl, isActive, string.Empty);



                    //productBrandData.BrandImageUrl = newBrand.BrandImageUrl;
                    //productBrandData.BrandUrl = newBrand.BrandUrl;
                    //productBrandData.BrandCatalogFileUrl = newBrand.BrandCatalogFileUrl;

                    //TblProductBrand.UpdateTblProductBrand(productBrandData);

                    return newBrand;
                }
                else
                    throw new InvalidOperationException("There is already a brand with same name");
            }
            catch (Exception ex)
            {
                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("Create caused server error: Parameters( ");
                logText = logText.Append("brandName -> ").Append(brandName);
                logText = logText.Append("brandDescription -> ").Append(brandDescription);
                logText = logText.Append("logoTemporaryFilePath -> ").Append(logoTemporaryFilePath);

                logText = logText.Append("isActive -> ").Append(isActive.ToString());
                logText = logText.Append("isFeatured -> ").Append(isFeatured.ToString());
                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("ProductBrand");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);

                throw ex;
            }
        }

        
        public static Manufacturer Create(string brandName, string brandDescription, string brandImage, string logoTemporaryFilePath, bool isActive, bool isFeatured, string brandCode, string brandBannerUrl)
        {
            try
            {
                int newBrandId = 0;

                brandName = Security.BindStringInput(brandName, SecurityLevel.Zero);
                string brandUrl = SiteUtility.CleanBrandName(brandName);
                brandDescription = Security.BindStringInput(brandDescription, SecurityLevel.Zero);
                logoTemporaryFilePath = Security.BindStringInput(logoTemporaryFilePath, SecurityLevel.Zero);
                string brandBannerTemporaryFilePath = Security.BindStringInput(brandBannerUrl, SecurityLevel.Zero);


                // counting how many brand has same name
                int count = ManufacturerDAO.GetProductBrandCountByName(brandName);
                string brandLogo = string.Empty;
                string brandBanner = string.Empty;

                if (!String.IsNullOrEmpty(logoTemporaryFilePath))
                {
                    brandLogo = ProductFileAccessUtility.UploadImage(ProductFileAccessUtility._brandLogoPath, logoTemporaryFilePath);
                }

                //if (!String.IsNullOrEmpty(brandBannerTemporaryFilePath))
                //{
                //    brandBanner = ProductFileAccessUtility.UploadImage(ProductFileAccessUtility._brandBannerPath, brandBannerTemporaryFilePath);
                //}

                // If no other brand has the same name, 
                // we create it.
                if (count <= 0)
                {
                    newBrandId = ManufacturerDAO.CreateNewTblProductBrand(brandName, brandDescription, brandLogo, brandUrl, isActive, brandBannerTemporaryFilePath);

                    //TblProductBrand productBrandData = new TblProductBrand(newBrandId, brandName, brandDescription, string.Empty, brandUrl,
                    //    string.Empty, catalogFileFormat, catalogFileName, isActive, isFeatured, false, DateTime.Now, Convert.ToDecimal(productPricePercentage));

                    Manufacturer newBrand = new Manufacturer(newBrandId, brandName, brandDescription, brandLogo, brandUrl, isActive, brandBannerTemporaryFilePath);



                    //productBrandData.BrandImageUrl = newBrand.BrandImageUrl;
                    //productBrandData.BrandUrl = newBrand.BrandUrl;
                    //productBrandData.BrandCatalogFileUrl = newBrand.BrandCatalogFileUrl;

                    //TblProductBrand.UpdateTblProductBrand(productBrandData);

                    return newBrand;
                }
                else
                    throw new InvalidOperationException("There is already a brand with same name");
            }
            catch (Exception ex)
            {
                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("Create caused server error: Parameters( ");
                logText = logText.Append("brandName -> ").Append(brandName);
                logText = logText.Append("brandDescription -> ").Append(brandDescription);
                logText = logText.Append("logoTemporaryFilePath -> ").Append(logoTemporaryFilePath);
                //logText = logText.Append("catalogTemporaryFilePath -> ").Append(catalogTemporaryFilePath);
                logText = logText.Append("isActive -> ").Append(isActive.ToString());
                logText = logText.Append("isFeatured -> ").Append(isFeatured.ToString());
                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("ProductBrand");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);

                throw ex;
            }
        }

        
        public static Manufacturer Create(string brandName, string brandDescription, string logoTemporaryFilePath, bool isActive, bool isFeatured, string brandCode, string brandBannerUrl)
        {
            return Create(brandName, brandDescription, logoTemporaryFilePath, logoTemporaryFilePath, isActive, isFeatured, brandCode, brandBannerUrl);
        }

        
        public static Manufacturer Update(Manufacturer manufacturer)
        {
            Manufacturer newBrand;
            newBrand = manufacturer;
            newBrand.BrandName = SiteUtility.CleanBrandName(newBrand.BrandName);
            ManufacturerDAO brandData = new ManufacturerDAO();
            brandData.Save(newBrand);
            return newBrand;
        }

        
        public static string ChangeLogoFile(string logoTemporaryFilePath, Manufacturer brand)
        {
            if (BrandFileAccessUtility.DeleteBrandLogo(brand))
            {
                if (brand.BrandImageUrl == string.Empty)
                {
                    FileInfo logoInfo = new FileInfo(HttpContext.Current.Server.MapPath(logoTemporaryFilePath));
                    if (logoInfo.Exists)
                    {
                        string cleanBrandName = SiteUtility.CleanBrandName(brand.BrandName);
                        brand.BrandImageUrl = cleanBrandName.ToLower() + logoInfo.Extension;
                    }
                }
                return BrandFileAccessUtility.UpdateBrandLogo(logoTemporaryFilePath, brand.BrandImageUrl);
            }
            return null;
        }

        
        public static void DeleteBrands(List<int> idList)
        {
            ManufacturerDAO.DeleteTblProductBrandList(idList);
        }

        
        public static void DeleteBrands(ReadWriteCustomCollection<Manufacturer> brands)
        {
            List<int> deleteIds = new List<int>();

            foreach (Manufacturer brand in brands)
            {
                BrandFileAccessUtility.DeleteBrandFiles(brand);
                deleteIds.Add(brand.ProductBrandId);
            }

            ManufacturerDAO.TemporaryDeleteBrands(deleteIds);
        }

        
        private static ReadWriteCustomCollection<Manufacturer> LoadFromCustomCollection(ECommerce.DAL.CustomCollection<Manufacturer> brandData)
        {
            ReadWriteCustomCollection<Manufacturer> result = new ReadWriteCustomCollection<Manufacturer>();

            for (int i = 0; i < brandData.Count; i++)
            {
                result.Add(brandData[i]);
            }

            return result;
        }

        
        public static Manufacturer GetProductBrandByName(string brandName)
        {
            if (!string.IsNullOrEmpty(brandName))
            {
                return ManufacturerDAO.GetTblProductBrandByProductBrandName(brandName);
            }
            else
                return null;
        }

        
        public static ReadWriteCustomCollection<Manufacturer> GetBackendBrandList(string orderBy, int startIndex, int pageSize)
        {
            return LoadFromCustomCollection(ManufacturerDAO.GetAllTblProductBrandPaged(orderBy, startIndex, pageSize));
        }

        
        public static int GetBackendBrandListCount()
        {
            return ManufacturerDAO.GetAllTblProductBrandPagedCount(string.Empty, 0, 0);
        }

        /**************************************************/
        public static Manufacturer GetById(int manufacturerId)
        {
            if (manufacturerId > 0)
            {
                return ManufacturerDAO.GetTblProductBrandByProductBrandId(manufacturerId);
            }
            else
                return null;
        }

        public static Manufacturer GetByBrandUrl(string brandUrl)
        {
            return ManufacturerDAO.GetTblProductBrandByProductBrandUrl(brandUrl);
        }

        public static ECommerce.DAL.CustomCollection<Manufacturer> GetByProductCategory(int categoryId)
        {
            return ManufacturerDAO.GetProductBrandsByPertnerCategory(categoryId);
        }

    }
}